import { message } from "antd";
import axios from "axios";
import { config } from "process";
import { getToken } from "../utils/user-token";
import { error } from "console";

const API_URL =
  process.env.NODE_ENV === "development" ? "" : "http://154.12.37.179:8887";
const instance = axios.create({
  baseURL: API_URL,
  timeout: 10 * 1000,
});
//request 拦截， 每次请求都带上token
instance.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = `Bearer ${getToken()}`; //JWT固定格式
    return config;
  },
  (error) => Promise.reject(error)
);
//response ；拦截器：统一处理errno和msg
instance.interceptors.response.use((res) => {
  const resData = (res.data || {}) as ResType;
  const { errno, data, msg } = resData;

  if (errno !== 0) {
    //错误提示
    if (msg) {
      message.error(msg);
    }
    throw new Error(msg);
  }
  return data as any;
});

export default instance;

export type ResType = {
  errno: number;
  data?: ResDataType;
  msg?: string;
};

export type ResDataType = {
  [key: string]: any;
};
